package net.aiform.security.resourcedetails;

import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * @author yanwt
 *
 */
public class EhCacheResourceCache implements InitializingBean {

	private static final String URL_RESOURCES = "URL";
	private static final String METHOD_RESOURCES = "METHOD";

	private Cache cache;
	private Logger log = LoggerFactory.getLogger(getClass());;
	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(cache, "cache is required");
	}
	/**
	 * �ӻ����л�ȡ��ԴResourcDetail����
	 */
	public ResourcDetail getResourcFromCache(String key_resourceName) {
		Element element = cache.get(key_resourceName);
		log.debug("get " + key_resourceName);
		if (element == null) {
			return null;
		} else {
			log.debug(key_resourceName + " -- " + element.getValue());
			return (ResourcDetail)element.getValue();
		}
	}
	/**
	 * ������Դ
	 * @param detail
	 */
	public void putResourcInCache(ResourcDetail detail) {
		Element element = new Element(detail.getResourceName(),detail);
		System.out.println("put " + detail.getResourceName() + " value: " + element.getValue());
		cache.put(element);
	}
	/**
	 * �ӻ����Ƴ���ԴResourcDetail����
	 * @param key_resourceName
	 */
	public void removeResourcFromCache(String key_resourceName) {
		cache.remove(key_resourceName);
	}

	public List<String> getUrlResources() {
		return getResourcesByType(URL_RESOURCES);
	}
	public List<String> getMethodResources() {
		return getResourcesByType(METHOD_RESOURCES);
	}

	@SuppressWarnings("unchecked")
	private List<String> getResourcesByType(String type) {
		List<String> resources = new ArrayList<String>();
		List<String> keysList = this.cache.getKeys();
		for (String key_resourceName : keysList) {
			ResourcDetail detail = getResourcFromCache(key_resourceName);
			if (detail != null && detail.getResourceType().equals(type)) {
				resources.add(detail.getResourceName());
			}
		}
		return resources;
	}

	/**
	 * @return the cache
	 */
	public Cache getCache() {
		return cache;
	}

	/**
	 * @param cache the cache to set
	 */
	public void setCache(Cache cache) {
		this.cache = cache;
	}

}
